package com.lcsuo.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.lcsuo.bean.Account;
import com.lcsuo.common.base.BaseController;
import com.lcsuo.service.AccountService;
import com.lcsuo.service.authority.TokenService;
import com.lcsuo.utils.Constants;
import com.lcsuo.utils.RestfulResponseBody;
import com.lcsuo.utils.seculity.Md5PwdEncoder;
import com.lcsuo.utils.web.RequestUtils;

/**
 * 用户注册、登录
 * @author Sorin
 *
 */
@RestController
@RequestMapping("/api/user")
public class AccountController extends BaseController{

	@Autowired
	private AccountService accountService;
	
	@Autowired 
	private TokenService tokenService;
	
	/**
	 * 注册
	 * @param mobileId
	 * @param password
	 * @param role
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/register", method=RequestMethod.POST)
	public RestfulResponseBody register(@RequestParam(required=true)String mobileId, 
			@RequestParam(required=true)String password, String role){
		accountService.register(mobileId, password, role);
		return setResponseEntity("注册成功！",Constants.resultType.SUCCESS);
	}
	
	/**
	 * 登录
	 * @param mobileId
	 * @param password
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/login", method=RequestMethod.POST)
	public RestfulResponseBody login(@RequestParam(required=true)String mobileId, 
			@RequestParam(required=true)String password, HttpServletRequest request){
		//密码MD5加密
		password = new Md5PwdEncoder().encodePassword(password);
		Account account = accountService.login(mobileId, password);
		if(account != null && password.equals(account.getPassword())){
			//登录成功，生成token并返回
			String token = tokenService.createToken(account.getId(), request.getHeader("User-Agent"), 
					RequestUtils.getIpAddr(request) , request.getSession().getId());
			RestfulResponseBody body = new RestfulResponseBody();
			body.setReason("登录成功！");
			body.setResultFlag(Constants.resultType.SUCCESS);
			body.put("token", token);
			return body;
		}else { //失败
			return setResponseEntity("手机号和密码不匹配！",Constants.resultType.ERROR);
		}
	}
}
